package com.zxd.interview.conrruentbook;

import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicIntegerArray;

/**
 * Atomic 原子数组 案例
 * 原子数组元素操作可以保证原子性
 */
public class AtomicArrayDemo{

    public static void main(String[] args) {
        AtomicInteger atomicInteger = new AtomicInteger();
        atomicInteger.incrementAndGet();


        AtomicIntegerArray atomicIntegerArray = new AtomicIntegerArray(1000);
        Decrementer decrementer = new Decrementer(atomicIntegerArray);
        Incrementer incrementer = new Incrementer(atomicIntegerArray);
        Thread[] threadAdd = new Thread[100];
        Thread[] threadDec = new Thread[100];
        for (int i = 0; i < 100; i++) {
            threadAdd[i] = new Thread(incrementer);
            threadDec[i] = new Thread(decrementer);
            threadAdd[i].start();
            threadDec[i].start();
        }

//        for (int i = 0; i < atomicIntegerArray.length(); i++) {
//            System.out.println(atomicIntegerArray.get(i));
//        }
    }

}

class Incrementer implements Runnable {

    private AtomicIntegerArray atomicIntegerArray;

    public Incrementer(AtomicIntegerArray atomicIntegerArray) {
        this.atomicIntegerArray = atomicIntegerArray;
    }

    @Override
    public void run() {
        for (int i = 1; i <= 100; i++) {
            int andIncrement = atomicIntegerArray.getAndIncrement(i);
            System.out.println(Thread.currentThread().getName()+" => "+andIncrement);

        }
    }
}

class Decrementer implements Runnable {

    private AtomicIntegerArray atomicIntegerArray;

    public Decrementer(AtomicIntegerArray atomicIntegerArray) {
        this.atomicIntegerArray = atomicIntegerArray;
    }

    @Override
    public void run() {
        for (int i = 1; i <= 100; i++) {
            atomicIntegerArray.getAndDecrement(i);
        }
    }
}